<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form size="small" ref="formBillGroupRef" :rules="rulesBill" :model="formBill" label-width="180px">


      <el-form-item label="款项名称" prop="purpose">
        <div style="display: flex; align-items: center;">
          <el-input v-model.trim="formBill.purpose" style="flex: 1;"></el-input>
          <el-button
            size="mini"
            icon="el-icon-refresh"
            @click="getLastTimeBill"
            style="margin-left: 8px; padding: 7px 8px;"
            :title="defaultValue.saveUpdSelect === 'save' ? '回填上次账单' : '仅新增时可用'"
            :disabled="defaultValue.saveUpdSelect !== 'save'">
          </el-button>
        </div>
      </el-form-item>

      <el-row>
        <el-col :span="10">
          <el-form-item label="账单类型" prop="price" >
            <el-select @change="typeIdChange" v-model="formBill.typeId" placeholder="请选择账单类型" :filterable="true" clearable>
              <el-option
                v-for="(item, index) in billTypeIdList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <div style="line-height: 40px">
            <span style="color: red">账单类型说明：</span>
            <span>{{typeExplain}}</span>
          </div>
        </el-col>
      </el-row>

      <el-form-item label="" >
        <span>最常用账单类型(单击选中)：</span>
        <span v-for="(item, index) in commonBillType">
          <el-button plain size="mini" type="success"  @click="buttonClickCommon(item.id)">
          {{item.name}}
        </el-button>
        </span>
      </el-form-item>


      <el-form-item label="使用人"  prop="userIdList">
        <el-select @change="selectChangedMemberFamily" v-model="formBill.userIdList" placeholder="请选择使用人" multiple clearable>
          <el-option
            v-for="item in memberFamilyList"
            :key="item.id"
            :label="item.userName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="" >
        <span>常用使用人(单击选中)：</span>
        <span v-for="(item, index) in memberFamilyList" :key="item.id">
          <el-button plain size="mini" type="success" :type="isUserSelected(item.id) ? 'primary' : 'success'"  @click="buttonUserClickCommon(item.id)">
          {{item.userName}}
        </el-button>
        </span>
      </el-form-item>

      <el-form-item label="金额" prop="price" >
        <el-input-number :min="0" v-model.trim="formBill.price"></el-input-number>
      </el-form-item>

      <el-form-item label="款项发生时间" prop="triggerTime" >
        <el-date-picker
          clearable
          v-model="formBill.triggerTime"
          placement="bottom-start"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="支出or收入" prop="incomeOrExpenditure" >
        <el-radio v-model="formBill.incomeOrExpenditure" :label="1">支出</el-radio>
        <el-radio v-model="formBill.incomeOrExpenditure" :label="2">收入</el-radio>
      </el-form-item>

      <el-form-item label="支出地点" prop="place" >
        <el-input v-model.trim="formBill.place"></el-input>
      </el-form-item>

      <el-form-item label="账单组">
        <el-select v-model="formBill.groupId" placeholder="请选择账单组" clearable>
          <el-option
            v-for="item in filteredBillGroupList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否入账" prop="entry" >
        <el-radio v-model="formBill.entry" :label="2">入账</el-radio>
        <el-radio v-model="formBill.entry" :label="1">不入账</el-radio>
      </el-form-item>


      <el-form-item label="核心账单" prop="core" >
        <el-radio v-model="formBill.core" :label="1">非核心</el-radio>
        <el-radio v-model="formBill.core" :label="2">核心账单</el-radio>
        <span v-if="formBill.price >= 120 && formBill.core === 2" style="color: #67C23A; margin-left: 10px;">
          <i class="el-icon-info"></i> 金额≥120，已自动设为核心账单
        </span>
      </el-form-item>

      <el-form-item label="支出方式" prop="modeOfExpenditure" >
        <el-radio v-model="formBill.modeOfExpenditure" :label="1">线上</el-radio>
        <el-radio v-model="formBill.modeOfExpenditure" :label="2">线下</el-radio>
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd" v-if="defaultValue.saveUpdSelect !== 'select'">{{defaultValue.title}}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>

</template>

<script>

  import http from '@/utils/http'
  import {clearInvalid} from "../../utils/utils"

  export default {
    name: "BillSaveUpd",
    data(){
      return {
        // 类型说明
        typeExplain: null,
        // 账单类型
        billTypeIdList: [],
        // 账单组
        billGroupList: [],
        // 家庭成员
        memberFamilyList: [],
        // 常用账单类型
        commonBillType: [],
        // 表格的默认值
        tableConfig: {
          // 关闭时销毁 Dialog 中的元素
          destroyOnClose: true,
          // 弹出框是否打开
          show: false,
          // 是否显示关闭按钮
          close: true,
          // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
          lockScroll: false,
          appendToBody: true,
        },
        // 默认值，进入页面后的值
        defaultValue: {
          // 弹出框标题
          title: '查看',
          // 保存还是修改or查看,取值有 select | save | upd
          saveUpdSelect: 'select'
        },
        // 提交的数据
        formBill:{
          userId: null,
          triggerTime: null,
          price: null,
          typeId: null,
          purpose: null,
          incomeOrExpenditure: null,
          place: null,
          groupId: null,
          entry: null,
          core: null,
          modeOfExpenditure: null,
          userIdList: null,
        },
        // 校验规则
        rulesBill: {
          triggerTime: [{ required: true, message: '请输入款项发生时间', trigger: 'blur' }],
          purpose: [{ required: true, message: '请输入款项名称', trigger: 'blur' }],
          price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
          typeId: [{ required: true, message: '请选择账单类型', trigger: 'change' }],
          incomeOrExpenditure: [{ required: true, message: '请选择是收入还是支出', trigger: 'change' }],
          userIdList: [{ required: true, message: '请选择使用人', trigger: 'change' }],
        },
      }
    },
    watch: {
      // 监听金额变化
      'formBill.price': {
        handler(newPrice) {
          // 金额≥120时自动设置为核心账单
          if (newPrice !== null && newPrice !== undefined && newPrice >= 120) {
            this.formBill.core = 2;
          }
        },
        immediate: true
      }
    },
    computed:{
      /**
       * 过滤后的账单组列表
       * 新增时：只显示 viewInfo = 1 的数据
       * 修改时：显示 viewInfo = 1 的数据 + 当前选中的数据（即使 viewInfo = 2）
       */
      filteredBillGroupList() {
        if (this.defaultValue.saveUpdSelect === 'upd' && this.formBill.groupId) {
          // 修改模式：显示所有 viewInfo=2 的数据 + 当前选中的数据
          return this.billGroupList.filter(item =>
            item.viewInfo === 2 || item.id === this.formBill.groupId
          );
        } else {
          // 新增模式：只显示 viewInfo=2 的数据
          return this.billGroupList.filter(item => item.viewInfo === 2);
        }
      }
    },
    methods: {
      /**
       * 检查用户是否被选中
       * @param {number|string} userId 用户ID
       * @returns {boolean} 是否选中
       */
      isUserSelected(userId) {
        if (!this.formBill.userIdList) return false;
        return this.formBill.userIdList.includes(userId);
      },
      /**
       * 打开弹出框之前
       * @param type 保存还是修改or查看,取值有 select \ save \ upd
       * @param obj 如果是修改和查看，则是详细数据,需要赋值
       */
      openBeforeBillPage(type, obj){
        this.defaultValue.saveUpdSelect = type
        this.clearOldData()
        this.init()

        if (type === 'save'){
          this.defaultValue.title = '新增账单'

        } else if (type === 'upd'){
          this.defaultValue.title = '修改账单'
          this.formBill = JSON.parse(JSON.stringify(obj))
          if (this.formBill.groupId === '-1'){
            this.formBill.groupId = null
          }


        } else {

        }

        this.tableConfig.show = true
        this.$store.commit('navigationListChange', ['开支管理', '账单', this.defaultValue.title])
      },
      /**
       * 先清理旧数据
       */
      clearOldData(){
        this.formBill = {
          userId: null,
          triggerTime: null,
          price: null,
          typeId: null,
          purpose: null,
          incomeOrExpenditure: null,
          place: null,
          groupId: null,
          entry: null,
          core: null,
          modeOfExpenditure: null,
          userIdList: null,
        }
      },
      /**
       * 最常用的几个类型被点击后
       * @param typeId 类型ID
       */
      buttonClickCommon(typeId){
        // console.log(typeId)
        this.formBill.typeId = typeId
        this.typeIdChange(typeId)
      },
      /**
       * 最常用的几个人员被点击后
       * @param userId 家庭成员ID
       */
      buttonUserClickCommon(userId){
        // 如果点击的是"全家"
        if (userId === '-1') {
          // 如果已经选中了全家，则取消选择
          if (this.formBill.userIdList && this.formBill.userIdList.includes('-1')) {
            this.formBill.userIdList = [];
          } else {
            // 否则只选择全家
            this.formBill.userIdList = ['-1'];
          }
        } else {
          // 如果当前已经选择了全家，先取消全家选择
          let newUserList = [...(this.formBill.userIdList || [])];
          const familyIndex = newUserList.indexOf('-1');
          if (familyIndex > -1) {
            newUserList.splice(familyIndex, 1);
          }

          // 切换当前用户的选择状态
          const userIndex = newUserList.indexOf(userId);
          if (userIndex > -1) {
            // 如果已选中，则取消选择
            newUserList.splice(userIndex, 1);
          } else {
            // 如果未选中，则添加
            newUserList.push(userId);
          }

          this.formBill.userIdList = newUserList;
        }

        // 触发选择变更逻辑
        this.selectChangedMemberFamily(this.formBill.userIdList);
      },
      /**
       * 账单类型被选中修改
       * @param value 被选中的值
       */
      typeIdChange(value){
        // 根据ID查询数组对象中的数据
        let obj = this.billTypeIdList.find(function (x) {
            return x.id === value
        })
        this.typeExplain = obj.remarks
      },
      /**
       * 初始化
       */
      init(){
        // 这样设置，设置的默认值为空，否则不会为空
        this.formBill.price = undefined
        this.getBillType()
        this.getMemberFamilyAll()
        this.getBillingGroupList()
        this.getMostCommonlyUsedType()
        if (this.defaultValue.saveUpdSelect === 'save'){
          this.getBillPaymentLocation()

          // 默认全家
          // this.formBill.userIdList = ['-1']
          this.formBill.triggerTime = new Date().toLocaleDateString('zh').replaceAll('/', '-')
          this.formBill.incomeOrExpenditure = 1
          this.formBill.entry = 2
          this.formBill.core = 1
          this.formBill.modeOfExpenditure = 1
        }
      },
      /**
       * 重置新增
       */
      resetAdd(){
        this.formBill.purpose = null
        this.formBill.price = undefined
        // this.formBill.userIdList = ['-1']
        this.formBill.userIdList = []
        this.formBill.typeId = null
        this.formBill.groupId = null
        this.formBill.incomeOrExpenditure = 1
        this.formBill.entry = 2
        this.formBill.core = 1
        this.formBill.modeOfExpenditure = 1
      },
      /**
       * 是保存还是修改
       */
      toSaveUpd(){
        if (this.defaultValue.saveUpdSelect === 'save'){
          this.saveBill()

        } else if (this.defaultValue.saveUpdSelect === 'upd'){
          this.updBill()

        } else {

        }
      },
      /**
       * 更新账单
       */
      updBill(){
        clearInvalid(this.formBill)
        this.formBill.userIdSet = this.formBill.userIdList.join(",")

        http.post("/bill/updBill", this.formBill).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("更新成功");
          this.$emit('getBillPageList', null)
          // 关闭弹出框
          this.tableConfig.show = false

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 新增账单
       */
      saveBill(){
        this.formBill.userIdSet = this.formBill.userIdList.join(",")

        http.post("/bill/saveBill", this.formBill).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("保存成功");
          this.$emit('getBillPageList', null)
          // 关闭弹出框,继续添加
          // this.tableConfig.show = false
          this.resetAdd()

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取 家庭成员
       */
      getMemberFamilyAll(){
        http.get("/user/getMemberFamilyAll", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.memberFamilyList = res.data
          let user = {id: '-1', userName: '全家'}
          this.memberFamilyList.unshift(user)

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取账单类型
       */
      getBillType(){
        http.get("/bill/getBillType", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.billTypeIdList = res.data

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取上一次的账单
       */
      getLastTimeBill(){
        http.post("/bill/getLastTimeBill", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          const lastBill = res.data;
          if (!lastBill || !lastBill.id) {
            this.$message.warning('暂无上次账单记录');
            return;
          }

          if (lastBill.groupId === '-1'){
            lastBill.groupId = null
          }

          // 先清空表单，再选择性赋值
          this.clearOldData();
          this.init();

          // 确保id为null
          lastBill.id = null;
          Object.keys(lastBill).forEach(key => {
            if (key !== 'id') {
              // 排除id字段
              this.formBill[key] = lastBill[key];
            }
          });

          this.$message.success('上次账单信息已回显');

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 不分页查询全部的账单组
       */
      getBillingGroupList(){
        http.get("/bill/getBillingGroupList", {

        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.billGroupList = res.data

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取默认的支付位置
       */
      getBillPaymentLocation(){
        http.get("/bill/getBillPaymentLocation", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          // 赋值
          this.formBill.place = res.data.value

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取最常用的五个类型
       */
      getMostCommonlyUsedType(){
        http.get("/bill/getMostCommonlyUsedType", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          // 赋值
          this.commonBillType = res.data

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 使用人被选中发生改变的时候,选中全家的时候只保留全家
       * @param value 选中的值
       */
      selectChangedMemberFamily(value){
        // 选中全家的时候。其他的直接干掉
        if (value.includes('-1')){
          this.formBill.userIdList = ['-1']
        }
      },
    }
  }
</script>

<style scoped>

/* 添加一些样式增强交互效果 */
.el-button {
  margin: 0 5px 5px 0;
  transition: all 0.3s;
}

.el-button--primary {
  font-weight: bold;
}

</style>
